/*
 * @(#)InvocationConnectorManager.java $version 2010. 8. 11
 *
 * Copyright 2007-2010 NHN Corp. All rights Reserved. 
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.nhncorp.usf.core.invoker;

import java.util.HashMap;
import java.util.Map;

import com.nhncorp.usf.core.config.ConnectorInfos;

/**
 * @author Web Platform Development Team
 */
public final class InvocationConnectorManager {
    private static InvocationConnectorManager instance;

    private static final Map<String, ConnectorHolder> INVOKERS = new HashMap<String, ConnectorHolder>();

    /**
     * Gets the single instance of InvocationConnectorManager.
     *
     * @return single instance of InvocationConnectorManager
     */
    public static synchronized InvocationConnectorManager getInstance() {
        if (instance == null) {
            instance = new InvocationConnectorManager();
        }

        return instance;
    }

    /**
     * Instantiates a new invocation connector manager.
     */
    private InvocationConnectorManager() {
    }

    /**
     * {@link Invoker} 추가 (Invoker는 Connector별로 관리)
     *
     * @param invokerId the invoker id
     * @param invoker   ther invoker object
     */
    public void putInvoker(String invokerId, ConnectorHolder invoker) {
        INVOKERS.put(invokerId, invoker);
    }

    /**
     * {@link Invoker} 추가 (Invoker는 Connector별로 관리)
     *
     * @param invokerId the invoker id
     * @param invoker   ther invoker object
     */
    public void putInvoker(String invokerId, Invoker invoker) {
        ConnectorHolder connectorHolder = new ConnectorHolder(invoker);
        INVOKERS.put(invokerId, connectorHolder);
    }


    /**
     * {@link Invoker} 추가
     *
     * @param connectorId the connector id
     * @return Invoker the Invoker object for connector id
     */
    public ConnectorHolder getRBConnectorHolder(String connectorId) {
        ConnectorHolder invoker = INVOKERS.get(connectorId);

        if (invoker == null) {
            String defaultConnector = ConnectorInfos.getInstance().getDefaultConnector();
            invoker = INVOKERS.get(defaultConnector);

            if (invoker == null) {
                throw new IllegalArgumentException("Default Invoker(" + defaultConnector + ") does not exist.");
            }

        }

        return invoker;
    }

    /**
     * Discard.
     */
    public void discard() {
        for (String key : INVOKERS.keySet()) {
            ConnectorHolder invoker = INVOKERS.get(key);
            invoker.dispose();
        }

        INVOKERS.clear();
    }

    /**
     * remove to invoker object
     *
     * @param connectorId the connector id
     */
    public void removeInvoker(String connectorId) {
        INVOKERS.remove(connectorId);
    }
}
